package com.leyou.lock;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁
 */
public class RedisLock {
     private StringRedisTemplate redisTemplate;
     private  String key;

     private String value="1";

     public RedisLock(StringRedisTemplate redisTemplate,String key){
        this.redisTemplate =redisTemplate;
        this.key=key;
     }
    /**
     * 获取锁
     */
    public Boolean tryLock(Integer timeout, TimeUnit timeUnit){
       String threadId= Thread.currentThread().getId()+ "";
       this.value=threadId;
       return redisTemplate.opsForValue().setIfAbsent(key,value,timeout,timeUnit);
    }

    /**
     * 删除锁
     */
    public void unLock(){
        String threadId = Thread.currentThread().getId()+"";
        String Id = redisTemplate.opsForValue().get(key);
        if (threadId.equals(Id)) {
            redisTemplate.delete(key);
        }
    }
}
